package com.wiloon.java.network.network.file.download.upload;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

/**
 * Created by Roy on 2016/3/17;
 */
public class FileUpload {
    private final static Logger logger = LoggerFactory.getLogger(FileUpload.class);
    private static String newLine = "\r\n";
    private static String BOUNDARY = "-------------------------107901260819347";

    /**
     * 向指定 URL 发送POST方法的请求
     * <p>
     * <p>
     * 发送请求的 URL
     * <p>
     * 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     *
     * @return 所代表远程资源的响应结果
     */
    public static String uploadFile(String urlStr, Map<String, String> textMap, String filesize, File file, String devid) {
        String returnMsg = "";
        HttpURLConnection conn = null;
        //boundary就是request头和上传文件内容的分隔符

        try {
            URL url = new URL(urlStr);
            logger.debug("HTTP (sendPost)——>urlStr:" + urlStr);
            conn = (HttpURLConnection) url.openConnection();
            // 设置为POST情
            conn.setRequestMethod("POST");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);

            // 设置请求头参数
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Charsert", "UTF-8");
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
            OutputStream out = new DataOutputStream(conn.getOutputStream());
            byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();// 定义最后数据分隔线

            // 文件上传
            StringBuilder fileBuf = new StringBuilder();
            fileBuf.append("--");
            fileBuf.append(BOUNDARY);
            fileBuf.append(newLine);
            appendFormLine(fileBuf, "devid", devid);
            appendFormLine(fileBuf, "file.name", file.getName());
            fileBuf.append("Content-Disposition: form-data;name=\"uploadfile\";filename=\"" + file.getName() + "\";filesize=\"" + filesize + "\"" + newLine);
            fileBuf.append("Content-Type:image/jpeg");
            fileBuf.append(newLine);
            logger.debug("HTTP fileBuf->" + fileBuf.toString());
            out.write(fileBuf.toString().getBytes());
            logger.debug("file buf done");
            //	InputStream in = fileInput.getInputStream();
            DataInputStream in = new DataInputStream(new FileInputStream(file));
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
            logger.debug("file write");
            // 最后添加换行
            //out.write(newLine.getBytes());
            in.close();
            out.write(end_data);
            out.flush();
            out.close();
            logger.debug("stream closed");
            // 读取返回数据
            StringBuffer backBuf = new StringBuffer();
            InputStreamReader inputStreamReader = new InputStreamReader(conn.getInputStream());
            logger.debug("got input stream.");
            BufferedReader reader = new BufferedReader(inputStreamReader);

            String line = null;
            while ((line = reader.readLine()) != null) {
                backBuf.append(line).append("\n");
            }
            returnMsg = backBuf.toString();
            reader.close();
            reader = null;
        } catch (Exception e) {
            System.out.println("failed to send post request" + urlStr);
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
        }
        logger.debug("response msg:" + returnMsg);
        return returnMsg;
    }

    private static void appendFormLine(StringBuilder stringBuffer, String key, String value) {
        String prefix = "Content-Disposition: form-data; name=";
        //prefix = "Content-Disposition: multipart/form-data;";
        stringBuffer.append(prefix + "\"" + key + "\"");
        stringBuffer.append(newLine);
        stringBuffer.append(newLine);
        stringBuffer.append(newLine);
        stringBuffer.append(value);
        stringBuffer.append(newLine);
        stringBuffer.append("--");
        stringBuffer.append(BOUNDARY);
        stringBuffer.append(newLine);

    }
}
